/*
stage('Build packages') {
  parallel 'conda CPU': {
    node('CPU') {
      sh "${docker_run} tlcpack/conda-cpu ./conda/build_cpu.sh
    }
  },
  'conda cuda': {
    node('CPU') {
      sh "${docker_run} tlcpack/conda-cuda90 ./conda/build_cuda.sh
      sh "${docker_run} tlcpack/conda-cuda100 ./conda/build_cuda.sh
    }
  }
// Here we could upload the packages to anaconda for releases
// and/or the main branch
}
*/


def update_docker(ecr_image, hub_image) {
  if (!ecr_image.contains("amazonaws.com")) {
    sh("echo Skipping '${ecr_image}' since it doesn't look like an ECR image")
    return
  }
  docker_init(ecr_image)
  sh(
    script: """
    set -eux
    docker tag \
      ${ecr_image} \
      ${hub_image}
    docker push ${hub_image}
    """,
    label: "Update ${hub_image} on Docker Hub",
  )
}

def deploy_docs() {
  // Note: This code must stay in the Jenkinsfile to ensure that it runs
  // from a trusted context only
  sh(
    script: '''
      set -eux
      rm -rf tvm-site
      git clone -b $DOCS_DEPLOY_BRANCH --depth=1 https://github.com/apache/tvm-site
      cd tvm-site
      git status
      git checkout -B $DOCS_DEPLOY_BRANCH

      git ls-tree HEAD docs/ --name-only | grep -vP '^docs/v\\d' | xargs rm -rf
      mkdir -p docs
      tar xf ../docs.tgz -C docs
      COMMIT=$(cat docs/commit_hash)
      git add .
      git config user.name tvm-bot
      git config user.email 95660001+tvm-bot@users.noreply.github.com
      git commit -m"deploying docs (apache/tvm@$COMMIT)"
      git status
    ''',
    label: 'Unpack docs and update tvm-site'
  )

  withCredentials([string(
    credentialsId: 'docs-push-token',
    variable: 'GITHUB_TOKEN',
    )]) {
    sh(
      script: '''
        cd tvm-site
        git remote add deploy https://$GITHUB_TOKEN:x-oauth-basic@github.com/apache/tvm-site.git
        git push deploy $DOCS_DEPLOY_BRANCH
      ''',
      label: 'Upload docs to apache/tvm-site'
    )
  }
}


def deploy() {
  stage('Deploy') {
    if (env.BRANCH_NAME == 'main' && env.DOCS_DEPLOY_ENABLED == 'yes') {
      node('CPU') {
        ws({{ m.per_exec_ws('tvm/deploy-docs') }}) {
          {{ m.download_artifacts(tag='docs', filenames=["docs.tgz"]) }}
          deploy_docs()
        }
      }
    }
    if (env.BRANCH_NAME == 'main' && env.DEPLOY_DOCKER_IMAGES == 'yes' && rebuild_docker_images && upstream_revision != null) {
      node('CPU') {
        ws({{ m.per_exec_ws('tvm/deploy-docker') }}) {
          try {
            withCredentials([string(
              credentialsId: 'dockerhub-tlcpackstaging-key',
              variable: 'DOCKERHUB_KEY',
            )]) {
              sh(
                script: 'docker login -u tlcpackstaging -p ${DOCKERHUB_KEY}',
                label: 'Log in to Docker Hub',
              )
            }
            def date_Ymd_HMS = sh(
              script: 'python3 -c \'import datetime; print(datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))\'',
              label: 'Determine date',
              returnStdout: true,
            ).trim()
            def tag = "${date_Ymd_HMS}-${upstream_revision.substring(0, 8)}"
            {% for image in images %}
            update_docker({{ image.name }}, "tlcpackstaging/{{ image.name }}:${tag}")
            {% endfor %}
          } finally {
            sh(
              script: 'docker logout',
              label: 'Clean up login credentials'
            )
          }
        }
      }
    }
  }
}
